package com.windy.dailynews.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.windy.dailynews.R;
import com.windy.dailynews.utils.BitmapUtils;
import com.windy.dailynews.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

public class ShowWebImageActivity extends BaseActivity
        implements ViewPager.OnPageChangeListener {
    private String urls;
    private List<String> mUrlList = new ArrayList<>();
    private List<View> mViewList = new ArrayList<>();
    private int current = -1;
    private String currentUrl = "";
    private int total = 0;
    private final static String PATH = Environment.getExternalStorageDirectory() + "/dailynews/image";

    @Bind(R.id.viewpager)
    ViewPager mViewPager;
    @Bind(R.id.txtCurrent)
    TextView txtCurrent;
    @Bind(R.id.txtSave)
    TextView txtSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showweb_image);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        urls = getIntent().getStringExtra("images");
        currentUrl = intent.getStringExtra("current");

        String[] urlArray = urls.split(",");

        for (int i = 0; i < urlArray.length; i++) {
            if (urlArray[i].equals(currentUrl)) {
                current = i;
            }
            if (!StringUtils.isEmpty(urlArray[i])) {
                mUrlList.add(urlArray[i]);
                View view = getLayoutInflater().inflate(R.layout.item_webview_image, null);
                mViewList.add(view);
                total++;
            }
        }
        MyPagerAdapter adapter = new MyPagerAdapter(this, mViewList, mUrlList);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(current);
        mViewPager.addOnPageChangeListener(this);
        txtCurrent.setText((current + 1) + "/" + total);
    }

    @OnClick(R.id.txtSave)
    void saveImage() {
        String url = mUrlList.get(current);
        String filename = StringUtils.getSubStr(url, 1);
        mViewList.get(current).setDrawingCacheEnabled(true);
        Bitmap bitmap = mViewList.get(current).getDrawingCache();

        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        String savepath = PATH + "/" + filename;
        BitmapUtils.saveBitmap(bitmap, savepath);
        Toast.makeText(this, "已保存到" + savepath, Toast.LENGTH_SHORT).show();
        mViewList.get(current).setDrawingCacheEnabled(false);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        current = position;
        txtCurrent.setText((position + 1) + "/" + total);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    class MyPagerAdapter extends PagerAdapter {
        private Context mContext;
        private List<View> mViewList;
        private List<String> mUrlsList;

        public MyPagerAdapter(Context context, List<View> listview, List<String> urlList) {
            mContext = context;
            mViewList = listview;
            mUrlsList = urlList;
        }

        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = mViewList.get(position);
            PhotoView photoview = (PhotoView) view.findViewById(R.id.photoview);
            Glide.with(mContext.getApplicationContext())
                    .load(mUrlsList.get(position))
                    .placeholder(R.drawable.article_default)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(photoview);
            photoview.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                @Override
                public void onViewTap(View view, float x, float y) {
                    ShowWebImageActivity.this.finish();
                }
            });
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (mViewList.size() <= position) {
                return;
            }
            container.removeView(mViewList.get(position));
        }
    }

}
